<?php

namespace app\admin\service;

use app\model\Admin;
use app\common\Error;
// use think\facade\Session;
use app\admin\service\RuleService;
use think\facade\Cache;
use app\common\Common;

/**
 * 登录注册服务类
 */
class LoginService
{
    private $adminModel;

    public function __construct(Admin $adminModel)
    {
        $this->adminModel = $adminModel;
    }

    /**
     * 用户后台登录
     * 
     * @dateTime 2022/09/06
     * @author zhixiang0215@126.com
     * @param string username
     * @param string password
     * @return array
     */
    public function adminUserLogin($params)
    {
        $username = addslashes(strip_tags($params['username']));
        $password = addslashes(strip_tags($params['password']));

        $data = $this->adminModel->getInfoByWhere(['name' => $username], 'id, rule_id, name, password,status');

        if (empty($data)) {
            return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::USER_NOT_EXIXTS];
        }
        if($data['status']==2){//用户状态 1正常 非1异常
            return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::IS_DEPAET_ERROR];
        }

        if (!password_verify($password, $data['password'])) {
            return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::PASSWORD_ERROR];
        }

        $token = Common::createToken($data['id']);

        $userInfo = [
            'token' => $token,
            'user_id' => $data['id'],
            'user_name' => $data['name'],
            'rule_id' => $data['rule_id']
        ];

        $menu = (new RuleService)->getMenuData($userInfo);
        if (empty($menu)) {
            return ['code' => Error::LOGIN_ERROR_CODE, 'message' => Error::LOGIN_ERROR];
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(3);
        $userInfo['menu_data'] = $menu;
        $redis->set($token, json_encode($userInfo), config('redis_key.admin_access_token_expire'));

        return $userInfo;
    }

    /**
     * 用户后台注册
     * 
     * @dateTime 2022/09/06
     * @author zhixiang0215@126.com
     * @param string username
     * @param string password
     * @return array
     */
    public function userRegister($params)
    {
        $username = addslashes(strip_tags($params['username']));
        $password = addslashes(strip_tags($params['password']));

        $data = $this->adminModel->getInfoByWhere(['name' => $username], 'id');

        if ($data) {
            return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::USERNAME_EXISTS];
        }

        $createData = [
            'password'   => password_hash($password, PASSWORD_DEFAULT),
            'name'       => $username,
            'created_at' => now()
        ];
        $id = $this->adminModel->edit($createData);

        if (!$id) {
            return ['code' => Error::NO_CHARGE_REQUIRED_CODE, 'message' => Error::PLEASE_CONTACT_THE_DEVELOPER];
        }
        return [];
    }
}